import os
import re
from datetime import datetime
from pathlib import Path
from openpyxl import Workbook
import sys
import logging
import traceback

import tkinter as tk
from tkinter import ttk, filedialog,messagebox

# 日志中打印具体的报错位置
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


# 检查文档中没有被打上标签的内容，并生成Excel

def main(git_path):
    print("main")
    if not os.path.exists(git_path):
        raise FileNotFoundError(f"文档仓路径不存在：{git_path}")

    now = datetime.now()
    # 获取 exe 所在目录（兼容打包前后两种环境）
    if getattr(sys, 'frozen', False):
        current_dir = os.path.dirname(sys.executable)  # 打包后 exe 路径
    else:
        current_dir = os.path.dirname(os.path.abspath(__file__))  # 开发环境路径

    # 拼接 Excel 文件路径，得到输出信息位置
    excel_path = os.path.join(current_dir, 'docs-info-' + now.strftime("%Y-%m-%d-%H-%M-%S") + '.xlsx')

    md_info = MdInfo(git_path, excel_path)
    md_info.operation()


# 处理当前md中责任田信息
class MdInfo:

    def __init__(self, git_path, excel_path):
        '''
            @param git_path: docs 仓路径
            @param excel_path: 责任田文档输出路径
        '''
        self.git_path = git_path
        self.excel_path = excel_path

    # 读取信息并处理
    def operation(self):
        # 加载工作簿
        wb = Workbook()
        # 激活工作表
        sheet = wb.active
        sheet.title = '文档目录及责任人'
        if not os.path.exists(self.git_path):
            sheet['A1'] = '本地代码仓路径错误'
            wb.save(self.excel_path)
            return
        sheet.append(
            ["文档路径", 'Kit', 'Subsystem', 'Owner', 'Designer', 'Tester', 'Adviser'])
        self.get_md_info(sheet)
        wb.save(self.excel_path)

    def get_md_info(self, sheet):
        # 判断当前路径是文件还是文件夹，是文件的话直接处理
        if os.path.isdir(self.git_path):
            directory_path = Path(self.git_path)
            for file_path in directory_path.rglob('*.md'):
                self.get_md_owner(file_path, sheet)
        elif os.path.isfile(self.git_path):
            self.get_md_owner(self.git_path, sheet)

    # 获取文档相关信息并输出到Excel
    def get_md_owner(self, file_path, sheet):
        md_info_line = ['', '', '', '', '', '', '']
        md_info_line[0] = str(file_path)

        # required_columns = ['Kit', 'Subsystem', 'Owner', 'SE', 'TSE']
        required_columns = ['Kit', 'Subsystem', 'Owner', 'Designer', 'Tester', 'Adviser']
        with open(file_path, 'r', encoding='utf-8') as file:
            file_content = file.read()
            i = 1
            for column in required_columns:
                pattern = f'<!--{column}:(.*?)-->\n'
                match = re.search(pattern, file_content)
                if match:
                    result = match.group(1).lstrip()
                    md_info_line[i] = result
                i = i + 1

        # 添加信息
        sheet.append(md_info_line)


# # 新增GUI类
# class MdCheckApp:
#     def __init__(self, root):
#         self.root = root
#         self.root.title("文档责任田检查工具")
#         self.git_path = tk.StringVar()
#
#         # 创建界面组件
#         ttk.Label(root, text="文档仓路径:").grid(row=0, column=0, padx=5, pady=5)
#         ttk.Entry(root, textvariable=self.git_path, width=50).grid(row=0, column=1, padx=5, pady=5)
#         ttk.Button(root, text="浏览", command=self.select_directory).grid(row=0, column=2, padx=5, pady=5)
#         ttk.Button(root, text="开始检查", command=self.run_check).grid(row=1, column=1, pady=10)
#
#     def select_directory(self):
#         path = filedialog.askdirectory()
#         if path:
#             self.git_path.set(path)
#
#     def run_check(self):
#         path = self.git_path.get()
#         if not path:
#             messagebox.showwarning("警告", "请先选择文档仓路径")
#             return
#
#         try:
#             main(path)  # 调用原有main函数
#             messagebox.showinfo("完成", f"检查完成，结果文件已生成在:\n{os.path.dirname(__file__)}")
#         except Exception as e:
#             messagebox.showerror("错误", str(e))

if __name__ == '__main__':
    git_path = 'D:\project\docs\zh-cn\\application-dev\\'
    main(git_path)
    # root = tk.Tk()
    # app = MdCheckApp(root)
    # root.mainloop()
